#!/bin/sh
#desc:Create DB for music
#package:odbgmusic
#type:local

IFS=$'\x0A'$'\x0D'
CONFIGFILE="/etc/opendomo/music.conf"
TMPPLIST=/tmp/bgmusic.tmplist
. $CONFIGFILE

if ! test -f "$STORAGE/nocover.jpg"; then
	cp /var/www/images/nocover.jpg $STORAGE/
fi

# Select works in automatic or manual 

case "$1" in
	create)	 
	if ! test -d $2; then
		echo "#ERRO The parameter isn't a folder"
	else
		cd $2
		DIR=`pwd`

		# Save manual entries and delete auto database
		if test -f $MUSICDB; then
			MENTRY=`cat $MUSICDB | grep "#manu#"` 
			rm -f $MUSICDB 2>/dev/null
			touch $MUSICDB 2>/dev/null
			
			echo "$MENTRY"  >>$MUSICDB
			echo ""		>>$MUSICDB
		fi

		for artist in *; do
			# In two case, if the parameter is a directory, come in.
			if test -d "$artist"; then
				cd "$artist" 
				for album in *; do 			
					#echo "Adding $artist to $MUSICDB"
					if test -d "$album"; then
						cd "$album"
						DIR=`pwd`
					
						# echo "#ALBUM:$album|auto"	>>$MUSICDB
						
						# Create a database with information
				
						for song in `ls -1 *.mp3`; do
							echo "#auto# \"$artist\" ($album) \"$DIR/$song\"" >>"$MUSICDB"
						done

						# Select a cover.jpg file, in the album folder or default file

						if test -f cover.jpg; then
							COVER="$DIR/cover.jpg"
						else
							COVER="$STORAGE/nocover.jpg"
						fi

						echo "#auto# \"$artist\" ($album) \"$COVER\"" 	>>"$MUSICDB"
						echo "" >>"$MUSICDB"
						cd ..
					fi

				done
			cd ..
			fi
		done

		# Change permisions and send log info

		chmod ugo+r $MUSICDB
		chown admin:admin $MUSICDB

		if test "$USER" == "admin"; then
			/bin/logevent info odsndtrack "Automatic music database created"
		fi
	fi
	;;
	add)
		
		ARTIST="$2"	
		ALBUM="$3"

		# If cover isn't specified select a default cover.

		if ! test -z "$4"; then
			COVER="$4"	
		else
			COVER="$STORAGE/nocover.jpg"
		fi

		# Add temporal song in database and cover
	
		for song in `cat $TMPPLIST`; do
			echo "#manu# \"$ARTIST\" ($ALBUM) \"$song\"" >>"$MUSICDB"	
		done

	
		echo "#manu# \"$ARTIST\" ($ALBUM) \"$COVER\"" >>"$MUSICDB"
		echo "" >>"$MUSICDB"
	;;	
esac

